package com.lihua.imgs.upload.demos.web;


import com.lihua.imgs.upload.config.ServerConfig;
import com.lihua.imgs.upload.utils.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author lihua
 * @date 2024/4/9 15:06
 **/
@Controller
@RequestMapping("/common")
public class UploadController {

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
            String formatDate = simpleDateFormat.format(new Date());
            // 服务器大前缀
            String filePath = System.getProperties().getProperty("user.home")+ "/"+"profile"+ "/" + "imgs" + "/" + formatDate;

            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", urls);
            ajax.put("fileNames", fileNames);
            ajax.put("originalFilenames", originalFilenames);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }
}

